﻿

#if MiaoImporter

using System;
using System.IO;
using UnityEditor;
namespace Miao
{
    /// <summary>
    /// 资产检视器.
    /// 提供编辑器下资产删除、移动、重命名和导入的监听
    /// </summary>
    public class AssetWatcher : AssetPostprocessor
    {
        /// <summary>
        /// 资产删除
        /// </summary>
        public static Action<string> onDeletedAsset;
        /// <summary>
        /// 资产导入
        /// </summary>
        public static Action<string> onImportedAsset;

        /// <summary>
        /// 资产移动(新资产路径, 旧资产路径)
        /// </summary>
        public static Action<string, string> onMovedAsset;
        /// <summary>
        /// 资产重命名(新资产路径, 旧资产路径)
        /// </summary>
        public static Action<string, string> onRenamedAsset;

        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            if (onImportedAsset != null)
            {
                foreach (string importedAsset in importedAssets) onImportedAsset(importedAsset);
            }
            if (onDeletedAsset != null)
            {
                foreach (string deletedAsset in deletedAssets) onDeletedAsset(deletedAsset);
            }

            if (onMovedAsset != null)
            {
                if (onRenamedAsset == null)
                {
                    for (int i = 0; i < movedAssets.Length; i++) onMovedAsset(movedAssets[i], movedFromAssetPaths[i]);
                }
                else
                {
                    for (int i = 0; i < movedAssets.Length; i++)
                    {
                        string newPath = movedAssets[i];
                        string oldPath = movedFromAssetPaths[i];
                        if (Path.GetDirectoryName(newPath) == Path.GetDirectoryName(oldPath)) onRenamedAsset(newPath, oldPath);
                        else onMovedAsset(newPath, oldPath);
                    }
                }
            }
            else
            {
                if (onRenamedAsset == null) return;
                for (int i = 0; i < movedAssets.Length; i++)
                {
                    string newPath = movedAssets[i];
                    string oldPath = movedFromAssetPaths[i];
                    if (Path.GetDirectoryName(newPath) == Path.GetDirectoryName(oldPath)) onRenamedAsset(newPath, oldPath);
                }
            }
        }
    }
}
#endif